# Copyright (c) 2005-2010, Paolo Amoroso (Aioe) <freedom@aioe.org>
# All rights reserved.
# Postfilter version 0.8.2

#!/usr/bin/perl

use strict;

use Net::DNS;
use Date::Parse;
use Digest;
use Digest::MD5;
use Digest::SHA1;


our (%hdr, $modify_headers, $body, $user, %config, %settings, %postersdefault );
our (%headlist, @quickref, @saved_headers, %whitelist, @distributions, %mysql, %forbidden_crosspost, %scoreset, %maxscore);
our (@nomoderation, @htmlallowed, @htmltags, %extracontent, %forbidden_headers, @forbidden_groups, %dnsbl, @localip );

########
#
# parsefile(): Parse posters.conf
#
#######

sub parsefile($)
{
	my $file = $_[0];


	my $HDR;
	open $HDR, "<$file" or return 55;

	my @lines = <$HDR>;
	my $conf;

	close $HDR;

	foreach ( @lines )
	{
		my $line = $_;
		$line =~ s/\#.+\n/\n/i;
		$line =~ s/\n/\ /g;
		$line =~ s/\}/\}\n/g;
		$line =~ s/[\ |\t]+/\ /g;
		$conf .= $line;
	}

	my $number = -1;

	while ( $conf =~ /group[\t|\ |\n]+\"([a-z|0-9|\-|.|\ |\:]+)\"[\ |\t]+\{(.+)\}\n/gi )
	{
		 $number++;
		 my $group = $1;
		 my $options = $2;

		 &log("debug", "Group number $number, name $group" );

		 $settings{$number}{'Name'} = $group;

		 &load_default_presets($number);

		 $options =~ s/\ +/\ /g;

		 while ( $options =~ /([a-z|0-9]+)\:[\t|\ ]+\"([a-z|0-9|\-|\@|\.]+)\"/gi )
		 {
			my $key   = lc($1);
			my $value = lc($2);

			my $success = &checkconfig( $key, $value );
			if ( $success == 0 )
			{  
				$settings{$number}{$key} = $value;
			 	&log("debug", "Configuration Key $key is set to $value" );
			}
			else
			{
				&log("err", "Syntax error inside parsers.conf, group $group, key $key: $value" );
				return 36;
			}
		 }
	}
	return 0;
}

sub checkconfig($$)
{
	my $key = $_[0];
	my $value = $_[1];

	my %items = (
        		"User" 			=> ".+",
        		"IPAddress"		=> "^[0-9|\.]+\$", 
        		"DomainName"		=> "^[a-z|0-9|\.]+\$",
			"MaxArticles"		=> "^[0-9]+\$",
			"MaxShortArticles"	=> "^[0-9]+\$",
			"MaxTotalErrors"	=> "^[0-9]+\$",
			"MaxShortErrors"	=> "^[0-9]+\$",
			"MaxTotalSize"		=> "^[0-9]+\$",
			"MaxShortSize"		=> "^[0-9]+\$",
			"MaxTotalGroups"	=> "^[0-9]+\$",
			"MaxShortGroups"	=> "^[0-9]+\$",
			"MaxTotalFollowups"	=> "^[0-9]+\$",
			"MaxShortFollowups"	=> "^[0-9]+\$",
			"Multipost"		=> "^[0-9]+\$"
		   );

	my $status = 0;

	foreach (keys %items)
	{
		if ( $key =~ /$_/i )
		{
			$status = 1;
			if ( $value !~ /$items{$_}/i )
			{
				&log("debug", "posters.conf error: key $key, value $value doesn't match $items{$_}");
				return 36;
			}
		}
	}

        if ($status == 0)
        {
		&log("debug", "posters.conf: Unknown key $key" );
                return 36;
        }

	return 0;

}


sub load_default_presets($)
{
	my $name = lc($_[0]);

	foreach ( keys %postersdefault )
	{
		my $key = lc($_);
		$settings{$name}{$key} = lc($postersdefault{$_});
	}

	return 0;
}
